const fs = require('fs'),
    md5 = require('md5');
var files = fs.readdirSync(process.cwd());
var count = 0;
var sd = require('silly-datetime');
let preveMd5 = null,
    fsWait = false;
const filePath = './';
console.log('正在监控:' + process.cwd());
fs.watch(process.cwd(), function (eventType, filename) {
    var currentMd5 = md5(fs.readFileSync(filePath + filename))
    if(eventType == 'rename'&& preveMd5 !=currentMd5)
    {
        var time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
        console.log('文件:' + filename + ' 被删除！');
        console.log('文件删除日期为' + time);
        return;
    }
    if (filename) {
        if (fsWait) return;//debounce函数，避免这种实时响应对应的频繁触发
        fsWait = setTimeout(() => {
            fsWait = false;
        }, 100)
        var currentMd5 = md5(fs.readFileSync(filePath + filename))
        if(currentMd5 != preveMd5&&eventType == 'change') 
        {
            var time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
            preveMd5 = currentMd5;
            console.log('文件:' + filename + ' 被修改！');
            console.log('文件更新日期为' + time);
            return;
        }
        if(currentMd5 != preveMd5&&eventType == 'rename')
        {
            var time = sd.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
            preveMd5 = currentMd5;
            console.log('文件:' + filename + ' 被创建！');
            console.log('文件更新日期为' + time);
            return;
        }
    }

}
)